package com.sky.task;

import com.sky.dto.OrdersCancelDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务
 */

@Component
@Slf4j
public class OrdersTask {


    @Autowired
    private OrderMapper orderMapper;

    /**
     * 定时任务：处理超时订单
     */
    @Scheduled(cron = "0 1 * * * ? ") //每分钟处理一次
    public void processTimeoutOrder(){
        log.info("处理超时订单：{}", LocalDateTime.now());

        //保存查询条件
        Integer status = Orders.PENDING_PAYMENT;                              //待付款状态
        LocalDateTime currentTime = LocalDateTime.now().plusMinutes(-15);     //当前时间减去15分钟
        //查询超时未付款订单
        List<Orders> TimeOutOrders = orderMapper.getTimeoutOrders(status,currentTime);

        //修改超时订单状态
        if(TimeOutOrders != null && TimeOutOrders.size() > 0){
            for (Orders order : TimeOutOrders) {
                //修改超时订单状态
                orderMapper.updateStatusByOrderId(Orders.CANCELLED,order.getId());
                //修改订单取消原因
                OrdersCancelDTO ordersCancelDTO = new OrdersCancelDTO();
                ordersCancelDTO.setId(order.getId());
                ordersCancelDTO.setCancelReason("支付超时");
                orderMapper.updateCancelReasonByOrderId(ordersCancelDTO);
            }
        }
    }

    /**
     * 定时处理派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ") //每天凌晨1点处理一次
    public void processDeliveryOrder(){
        log.info("处理派送中的订单：{}", LocalDateTime.now());
        //保存查询条件
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime currentTime = LocalDateTime.now().plusMinutes(-60);
        //查询派送中的订单
        List<Orders> deliveryOrders = orderMapper.getTimeoutOrders(status,currentTime);
        //修改订单状态
        if(deliveryOrders != null && deliveryOrders.size() > 0){
            for (Orders order : deliveryOrders) {
                orderMapper.updateStatusByOrderId(Orders.COMPLETED,order.getId());
            }
        }
    }
}
